package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    static String driver;// = "com.mysql.cj.jdbc.Driver";
    static String url;// = "jdbc:mysql://localhost:3306/person?characterEncoding=utf8&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false";
    static String user;// = "root";
    static String password;// = "root";
    Connection conn;
    static {
        init();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    static void init(){
        Properties params = new Properties();
        String configFile = "database.properties";      //配置文件路径
        //加载配置文件到输入流中
        /**
         * BaseDao.class 获取该类的类对象
         * getClassLoader() 获取类加载器
         * getResourceAsStream() 将参数对象转为InputStream类型
         */
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
        try{
            //从输入流中读取属性列表
            params.load(is);
        }catch (IOException e){
            e.printStackTrace();
        }
        //根据指定的获取对应的值
        driver = params.getProperty("driver");
        url=params.getProperty("url");
        user=params.getProperty("username");
        password=params.getProperty("password");
    }
    public Connection getConnection(){
        if (conn == null){
            try {
                conn = DriverManager.getConnection(url,user,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }
    public void closeAll(Connection conn, Statement stmt, ResultSet rs){
        try{
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
